package handler

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"honghu_be/common"
	"honghu_be/dal"
	"honghu_be/model"
	"honghu_be/model/vo"
)

func GetBox(c *gin.Context) {
	req := &model.GetBoxRequest{}
	if err := c.ShouldBindUri(req); err != nil {
		c.JSON(400, err.Error())
		return
	}

	resp, err := getBox(c, req.BoxId)
	if err != nil {
		common.WriteError(c, err)
		return
	}
	c.JSON(200, resp)
}

func getBox(c *gin.Context, boxId string) (*model.GetBoxResponse, error) {
	pos, err := dal.GetBoxes(c, &dal.GetBoxesRequest{
		BoxId: cast.ToInt(boxId),
	})
	if err != nil {
		return nil, err
	}
	if len(pos) == 0 {
		return nil, errors.New(fmt.Sprintf("box_%s not found", boxId))
	}
	return &model.GetBoxResponse{
		Meta: common.MetaOk,
		Box:  vo.ToBoxVo(pos[0]),
	}, nil
}
